<template>
  <div class="products-page">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">商品管理</h1>
        <p class="text-gray-600 mt-2">管理系统商品信息和库存</p>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6 border border-gray-200">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
          <div>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索商品名称..."
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @input="handleSearch"
            />
          </div>
          <div>
            <select
              v-model="selectedCategory"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有分类</option>
              <option value="电子产品">电子产品</option>
              <option value="电脑配件">电脑配件</option>
              <option value="音频设备">音频设备</option>
              <option value="办公用品">办公用品</option>
            </select>
          </div>
          <div>
            <select
              v-model="selectedBrand"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有品牌</option>
              <option value="Apple">Apple</option>
              <option value="Cherry">Cherry</option>
              <option value="Sony">Sony</option>
              <option value="LG">LG</option>
            </select>
          </div>
          <div>
            <select
              v-model="sortBy"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleSort"
            >
              <option value="createdAt">创建时间</option>
              <option value="price">价格</option>
              <option value="name">名称</option>
              <option value="rating">评分</option>
            </select>
          </div>
        </div>
        <div class="flex justify-between items-center">
          <div class="flex gap-2">
            <button
              @click="fetchProducts"
              class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              刷新
            </button>
            <button
              @click="showAddProductModal = true"
              class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
            >
              添加商品
            </button>
          </div>
          <div class="text-sm text-gray-600">
            共 {{ total }} 个商品
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <div
          v-for="product in products"
          :key="product.id"
          class="bg-white rounded-lg shadow-md border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow"
        >
          <!-- 商品图片 -->
          <div class="relative h-48 bg-gray-200">
            <img
              :src="product.images[0]"
              :alt="product.name"
              class="w-full h-full object-cover"
            />
            <div class="absolute top-2 right-2">
              <span :class="getStatusClass(product.status)" class="px-2 py-1 text-xs font-medium rounded-full">
                {{ getStatusText(product.status) }}
              </span>
            </div>
            <div class="absolute top-2 left-2 flex items-center bg-white bg-opacity-90 rounded-full px-2 py-1">
              <svg class="w-4 h-4 text-yellow-400 fill-current" viewBox="0 0 20 20">
                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
              </svg>
              <span class="ml-1 text-xs font-medium text-gray-700">{{ product.rating }}</span>
            </div>
          </div>

          <!-- 商品信息 -->
          <div class="p-4">
            <h3 class="text-lg font-semibold text-gray-900 mb-2 line-clamp-2">{{ product.name }}</h3>
            <p class="text-sm text-gray-600 mb-3 line-clamp-2">{{ product.description }}</p>
            
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center space-x-2">
                <span class="text-lg font-bold text-red-600">¥{{ formatPrice(product.price) }}</span>
                <span v-if="product.originalPrice > product.price" class="text-sm text-gray-500 line-through">
                  ¥{{ formatPrice(product.originalPrice) }}
                </span>
              </div>
              <span class="text-sm text-gray-500">库存: {{ product.stock }}</span>
            </div>

            <div class="flex items-center justify-between text-xs text-gray-500 mb-3">
              <span>{{ product.brand }}</span>
              <span>{{ product.category }}</span>
            </div>

            <!-- 操作按钮 -->
            <div class="flex space-x-2">
              <button
                @click="viewProduct(product.id)"
                class="flex-1 px-3 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
              >
                查看
              </button>
              <button
                @click="editProduct(product.id)"
                class="flex-1 px-3 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition-colors"
              >
                编辑
              </button>
              <button
                @click="deleteProduct(product.id)"
                class="flex-1 px-3 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 transition-colors"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="mt-8 flex justify-center">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
          <button
            @click="prevPage"
            :disabled="currentPage === 1"
            class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
          >
            上一页
          </button>
          <button
            v-for="page in visiblePages"
            :key="page"
            @click="goToPage(page)"
            :class="[
              page === currentPage
                ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50',
              'relative inline-flex items-center px-4 py-2 border text-sm font-medium'
            ]"
          >
            {{ page }}
          </button>
          <button
            @click="nextPage"
            :disabled="currentPage >= totalPages"
            class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
          >
            下一页
          </button>
        </nav>
      </div>
    </div>
  </div>
</template>

<script setup>
// 响应式数据
const products = ref([])
const loading = ref(false)
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedBrand = ref('')
const sortBy = ref('createdAt')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const totalPages = ref(0)

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 方法
const fetchProducts = async () => {
  try {
    loading.value = true
    const response = await $fetch('/api/products', {
      query: {
        page: currentPage.value,
        limit: pageSize.value,
        search: searchQuery.value,
        category: selectedCategory.value,
        brand: selectedBrand.value,
        sortBy: sortBy.value,
        sortOrder: 'desc'
      }
    })
    
    products.value = response.data.products
    total.value = response.data.pagination.total
    totalPages.value = response.data.pagination.totalPages
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = useDebounceFn(() => {
  currentPage.value = 1
  fetchProducts()
}, 300)

const handleFilter = () => {
  currentPage.value = 1
  fetchProducts()
}

const handleSort = () => {
  fetchProducts()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchProducts()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchProducts()
  }
}

const goToPage = (page) => {
  currentPage.value = page
  fetchProducts()
}

const formatPrice = (price) => {
  return price.toLocaleString()
}

const getStatusClass = (status) => {
  const classes = {
    in_stock: 'bg-green-100 text-green-800',
    out_of_stock: 'bg-red-100 text-red-800',
    low_stock: 'bg-yellow-100 text-yellow-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const texts = {
    in_stock: '有库存',
    out_of_stock: '缺货',
    low_stock: '库存不足'
  }
  return texts[status] || status
}

const viewProduct = (productId) => {
  navigateTo(`/products/${productId}`)
}

const editProduct = (productId) => {
  // 实现编辑商品功能
  console.log('编辑商品:', productId)
}

const deleteProduct = (productId) => {
  // 实现删除商品功能
  if (confirm('确定要删除这个商品吗？')) {
    console.log('删除商品:', productId)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchProducts()
})

// 监听路由变化
watch(() => useRoute().query, () => {
  fetchProducts()
}, { deep: true })
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  background-color: #f8fafc;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 